package cn.jhc.teachingquality.net.teaching;

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jhc.teachingquality.Global;
import cn.jhc.teachingquality.bean.TeachingLog;
import cn.jhc.teachingquality.net.TeachingQualityRequest;

/**
 * 列出已审核教学日志的请求。
 * Created by luyanfei on 16-4-9.
 */
public class ListCheckedTeachingLogsRequest extends TeachingQualityRequest<List<TeachingLog>> {
    private static final String LIST_CHECKED_TEACHING_LOGS_URL =
            Global.URL_PREFIX + "/pjJxrzAction!list.shtml";

    public ListCheckedTeachingLogsRequest(Response.Listener<List<TeachingLog>> listener) {
        super(Method.POST, LIST_CHECKED_TEACHING_LOGS_URL, listener);
    }

    @Override
    protected List<TeachingLog> handleResponse(Document document) {
        List<TeachingLog> teachingLogs = new ArrayList<>();
        Elements totalLogs = document.select("#listBody tbody tr");
        for(Element element : totalLogs){
            String hiddenId;
            String courseName;
            int weekSeq;
            String periodDesc;
            String className;
            try {
                hiddenId = element.getElementsByAttributeValue("name", "idKeys").first().val().trim();
                courseName = element.getElementsByAttributeValue("name", "kcMc").first().text().trim();
                weekSeq = Integer.valueOf(element.getElementsByAttributeValue("name", "zc").first().text().trim());
                periodDesc = element.getElementsByAttributeValue("name", "skSj").first().text().trim();
                className = element.getElementsByAttributeValue("name", "bjMc").first().text().trim();
            } catch (NullPointerException npe){
                Log.w(Global.LOG_TAG, "Skip one tr element in checked teaching log lists.");
                continue;
            }
            teachingLogs.add(new TeachingLog(hiddenId, courseName, weekSeq, periodDesc, className));
        }
        Log.w(Global.LOG_TAG, "Fetched " + teachingLogs.size() + " checked teaching logs.");
        return teachingLogs;
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> map = new HashMap<>();
        //同时显示400条记录
        map.put("page.pageSize", Global.PAGE_SIZE);
        return map;
    }
}
